import ErrorComp from '@/components/common/error-comp';
import LeftToRightView from '@/components/common/motion/left-to-right-view';
import QueryImage from '@/components/common/query-image';
import { Button } from '@/components/ui/button';
import AddRemoveCart from '@/components/user/add-remove-cart';
import { getCart } from '@/service/query/cart';
import { getProductById } from '@/service/query/product';
import Link from 'next/link';
import { z } from 'zod';

export const metadata = {
  title: '外卖详情',
};

const paramSchema = z.object({
  id: z.coerce.number().int().positive(),
});

export default async function Page({
  params,
}: { params: Promise<{ id: string }> }) {
  const paramsRes = paramSchema.safeParse(await params);
  if (!paramsRes.success) return <ErrorComp message="参数错误" />;

  const { result, error } = await getProductById(paramsRes.data.id);
  if (error) return <ErrorComp message={error.message} />;

  const { result: cart, error: cartError } = await getCart(result.shopId);

  return (
    <LeftToRightView>
      <div className="bg-background min-h-screen shadow-lg p-10 pt-20 space-y-10">
        <Link href={`/detail-shop/${result.shopId}`}>
          <Button variant="ghost" className="group">
            <span className="i-ri-arrow-left-s-line group-hover:-translate-x-1 transition-transform" />
            返回
          </Button>
        </Link>
        <div className="columns-3 gap-4 space-y-4">
          {result.imageKeys.map((imageKey) => (
            <QueryImage key={imageKey} imageKey={imageKey} />
          ))}
        </div>
        <div className="flex justify-between">
          <div className="space-y-5">
            <div className="font-bold text-xl">{result.name}</div>
            <div className="text-muted-foreground text-sm">
              {result.description}
            </div>
          </div>
          <div className="flex flex-col justify-between items-center gap-4">
            <div className="font-bold text-nowrap text-xl">
              {result.price}元
            </div>
            <div>
              <div className="text-sm">加入购物车</div>
              {cartError ? (
                <div>无法获取购物车信息</div>
              ) : (
                <AddRemoveCart
                  shopId={result.shopId}
                  productId={result.id}
                  count={cart[result.id.toString()] ?? 0}
                />
              )}
            </div>
          </div>
        </div>
      </div>
    </LeftToRightView>
  );
}
